﻿package ua.mihaylenko.canvas.gui 
{
	
	import flash.display.BitmapData;
	import flash.display.Stage;
	import flash.display.Sprite;
	import flash.display.MovieClip;
	import com.adobe.images.JPGEncoder;
	import com.adobe.images.BMPEncoder;
	import flash.net.navigateToURL;
	import flash.display.Sprite;
	import flash.events.*;
	import flash.net.*;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	import ua.mihaylenko.canvas.data.DataManager;
	/**
	 * ...
	 * @author Anton Bodrichenko
	 */
	public class Screenshot 
	{
		private var downloadURL:URLRequest;
        private var file:FileReference;


		private var serverUniqueFileName:String;

		//Need to change the name to your sepcified server 
		private var serverPath:String = DataManager.getInatsnce().uploadDir;
		//var serverPath:String = "http://localhost/";


		private var timer:Timer;
		private var isDownloadProgress = false;

		public function Screenshot() 
		{
			//btnSave.addEventListener(MouseEvent.CLICK, clickHandlerBtnSave);
		}
		

////////////////////////////////////////////////////////////////////////////
//Initialization

////////////////////////////////////////////////////////////////////////////
// Call this public function On Button Save 
////////////////////////////////////////////////////////////////////////////


		public function createBitmap(displObj:Sprite):void
		{
			
			serverUniqueFileName=DataManager.getInatsnce().filePrevName;
			createJPG(displObj, 85, DataManager.getInatsnce().filePrevName);
			
			//Similarly Save PNG could be added into the system
		}



		public function timerHandler(event:TimerEvent)
		{
			
		}

		public function timerCompleteHandler(event:Event)
		{
			isDownloadProgress=false;
		}


		//////////////////////////////////////////////////////////////////////////////////////////////////////
		public function FileReference_download() :void
		{   
			GUIMain.THIS.navigate();
			downloadURL = new URLRequest();
			downloadURL.url = serverPath+serverUniqueFileName;

			file = new FileReference();
			configureListeners(file);
			//file.download(downloadURL, serverUniqueFileName+comboFileFormat.selectedItem.label);
		}

		public function configureListeners(dispatcher:IEventDispatcher)
		{
			dispatcher.addEventListener(Event.SELECT, selectHandler);
			dispatcher.addEventListener(Event.COMPLETE, completeHandler);
		}

		public function getUniqueFileName(fileName:String):String
		{
			var date:Date = new Date();
			return fileName+date.getTime();
		}

		public function completeHandler(event:Event):void 
		{
			//mcSavingMsg.visible=false;
			deleteDownLoadFile(serverUniqueFileName);
		}

		public function selectHandler(event:Event):void {
			var file:FileReference = FileReference(event.target);
			trace("selectHandler: name=" + file.name + " URL=" + downloadURL.url);
		}



		//After file is downloaded on Desktop Call this public function to delete file from the server
		public function deleteDownLoadFile(fileName:String):void
		{
			return;
		}
		public function deleteTempServerFile(evt:Event):void
		{
			var write:* = evt.target.data.write;
			trace ('DeleteFileWrite ' + write);
		}

		public function sendIOErrorDeleteFile(event:Event):void
		{
		
		}
		



		//Fired when URL Loading Complete
		public function imageUrlLoaderComplete(evt:Event):void
		{
			trace("imageUrlLoaderComplete")
			var write:* = evt.target.data.write;
			if(write=="yes")
				FileReference_download();
		}

		public function sendIOError(event:Event):void
		{
			trace("Error occured");
		}


		////////////////////////////////////////////////////////////////////////////////////
		// Creating JPG Image
		////////////////////////////////////////////////////////////////////////////////////
		public function createJPG(m:Sprite, q:Number, fileName:String="snapshot.jpg"):void
		{
			serverUniqueFileName=DataManager.getInatsnce().filePrevName;
			var jpgSource:BitmapData = new BitmapData (m.width, m.height);
			jpgSource.draw(m);
			var jpgEncoder:JPGEncoder = new JPGEncoder(q);
			var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
			
			var header:URLRequestHeader = new URLRequestHeader ("Content-type", "application/octet-stream");
			var jpgURLRequest:URLRequest = new URLRequest (serverPath+"jpg_encoder_download.php?name=" + fileName);		
			
			jpgURLRequest.requestHeaders.push(header);				
			jpgURLRequest.method = URLRequestMethod.POST;				
			jpgURLRequest.data = jpgStream;
			
			
			var jpgURLLoader:URLLoader = new URLLoader();
			jpgURLLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
			jpgURLLoader.addEventListener( Event.COMPLETE, imageUrlLoaderComplete );
			jpgURLLoader.addEventListener( IOErrorEvent.IO_ERROR, sendIOError );
			jpgURLLoader.load( jpgURLRequest );
		}

		/////////////////////////////////////////////////////////////////////////////////////////
		//Creating bitmap images
		/////////////////////////////////////////////////////////////////////////////////////////

	}
}